package com.ikingtech.framework.sdk.cluster.node.handler;

import com.ikingtech.framework.sdk.cluster.client.ClusterClient;
import com.ikingtech.framework.sdk.cluster.node.ClusterNode;
import com.ikingtech.framework.sdk.cluster.node.ClusterNodeManager;
import com.ikingtech.framework.sdk.utils.Tools;
import io.netty.buffer.ByteBuf;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class ClusterNodeHeartBeatMessageHandler implements ClusterNodeMessageHandler {

    private final ClusterNodeManager nodeManager;

    private final ClusterClient client;

    @Override
    public void handle(Object message) {
        ClusterNodeHeartBeatMessage heartBeatMessage = Tools.Json.toBean(((ByteBuf) message).toString(Charset.defaultCharset()), ClusterNodeHeartBeatMessage.class);
        if (null == heartBeatMessage) {
            log.warn("[CLUSTER]heart beat message is null");
            return;
        }
        ClusterNode node = this.nodeManager.get(heartBeatMessage.getAddress(), heartBeatMessage.getPort());
        if (null == node) {
            log.debug("[CLUSTER][NODE-HEAR-BEAT]new node(address={}, port={}) detected, put into node list", heartBeatMessage.getAddress(), heartBeatMessage.getPort());
            node = new ClusterNode();
            node.setAddress(heartBeatMessage.getAddress());
            node.setPort(heartBeatMessage.getPort());
            this.client.newConnection(node);
        } else {
            log.debug("[CLUSTER][NODE-HEAR-BEAT]from node(address={}, port={})", heartBeatMessage.getAddress(), heartBeatMessage.getPort());
            node.setAddress(heartBeatMessage.getAddress());
            node.setPort(heartBeatMessage.getPort());
        }
        this.nodeManager.put(node);
    }
}
